<?php

namespace App\Listeners;

use App\Enum\LogsEnum;
use App\Enum\OrderEnum;
use App\Events\OrderOrd;
use App\Models\LogsModel;
use App\Services\RedisKeysService;
use Exception;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class OrderOrdNotification
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  OrderOrd  $event
     * @return void
     */
    public function handle(OrderOrd $event)
    {
        $fromBackend = false;$adminId = 0;$adminName='';

        $orderInfo = $event->orderInfo['result'];
        $driverId = $orderInfo->driver_id;
        $userId = $orderInfo->user_id;

        //如果是后台请求取消订单
        if( isset($event->adminInfo['admin_id']) && !empty($event->adminInfo['admin_id'])){
            $adminId    = $event->adminInfo['admin_id'];
            $adminName  = $event->adminInfo['admin_name'];
            $fromBackend = true;
        }
        // 添加订单日志 20230901 by LC
        LogsModel::query()->create([
            'type'      => LogsEnum::LOGS_TYPE_ORDER,
            'ref_id'    => $orderInfo->id,
            'ref_no'    => $orderInfo->order_no,
            'user_id'   => $fromBackend?$adminId:$orderInfo->driver_id,
            'user_type' => $fromBackend?LogsEnum::LOGS_USER_TYPE_BACKEND:LogsEnum::LOGS_USER_TYPE_DRIVER,
            'username'  => $fromBackend?$adminName:LogsEnum::LOGS_USER_NAME,
            'content'   => '核销订单：状态'.'('.OrderEnum::STATUS_NAME[$orderInfo->status].')',
        ]);
         // 删除订单列表的缓存
        if( !$fromBackend ) {
            try {
                // 去掉用户订单的缓存 20230926 by LC
                (new RedisKeysService())->deleteOrderListKey($userId,$driverId);
            }catch (Exception|NotFoundExceptionInterface|ContainerExceptionInterface $e){
                Log::error(sprintf('订单核销-删除keys失败,ORDER-ID=%d',$orderInfo->id));
            }
        }

    }
}
